package cn.fl.carloan.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.fl.carloan.service.IOdrShopClueInfoService;
import cn.fl.carloan.transform.OdrShopClueInfoVOTransform;
import cn.fl.carloan.vo.OdrShopClueInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import fl.carloan.facade.carloan.api.IOdrShopClueInfoApiService;
import fl.carloan.facade.carloan.condition.OdrShopClueInfoQC;
import fl.carloan.facade.carloan.constant.OdrShopClueInfoConstant;
import fl.carloan.facade.carloan.dto.OdrBscInfoDTO;
import fl.carloan.facade.carloan.dto.OdrShopClueInfoDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.api.ISysRegionApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.comm.facade.framework.dto.SysRegionDTO;
import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.dto.SysOrgDTO;


/**
 * @Description: 商家线索管理表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class OdrShopClueInfoServiceImpl implements IOdrShopClueInfoService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(OdrShopClueInfoServiceImpl.class);

	/**
	 * 自定义 API 自行注入需要的API服务
	 */
	//@Autowired
	//private I自定义ApiService 自定义ApiService;

	@Autowired
	private IOdrShopClueInfoApiService odrShopClueInfoApiService;

    /**
     * 字典服务层BEAN
     */
    @Autowired
    private ISysOrgApiService sysOrgApiService;
    
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    
    @Autowired
	private ISysRegionApiService sysRegionApiService;
    
    
	@Override
	public OdrShopClueInfoVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "获取对象主键不能为空!");
		}
		//TODO 业务逻辑
		OdrShopClueInfoDTO dto = null;//this.自定义ApiService.selectOdrShopClueInfoDTOById(id);
		return OdrShopClueInfoVOTransform.toVO(dto);
	}

	@Override
	public Long add(OdrShopClueInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不存在!");
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"新增对象不存在!");
		};
		return this.odrShopClueInfoApiService.add(OdrShopClueInfoVOTransform.toDTO(entity));
		//TODO 业务逻辑
	//	return null;
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "removeById", "删除对象主键不能为空!");
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"删除对象主键不能为空!");
		};
		//return this.odrShopClueInfoApiService.removeOdrShopClueInfoDTOById(id);
		//TODO 业务逻辑
		return false;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
		if(CollectionUtils.isEmpty(ids)){
			BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"删除对象主键不能为空!");
		};
		return false;
    }

	@Override
	public boolean modify(OdrShopClueInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象不能为空!");
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"修改对象不能为空!");
		};
		//return this.odrShopClueInfoApiService.modifyOdrShopClueInfoDTO(OdrShopClueInfoVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return false;
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page){
			page = new Pager();
		}
		page = this.odrShopClueInfoApiService.searchOdrShopClueInfoListPage(page);
		
		List<OdrShopClueInfoDTO> odrShopClueInfoDTOList = (List<OdrShopClueInfoDTO>) page.getResultList();
		if(CollectionUtils.isNotEmpty(odrShopClueInfoDTOList)){
			this.setOdrBscInfoOrgInfo(odrShopClueInfoDTOList, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd() );
			List<OdrShopClueInfoVO> voList = OdrShopClueInfoVOTransform.toVOList(odrShopClueInfoDTOList);
			
			String sysCd = CurrentThreadContext.getCurrentSysCd();
			String orgCd = CurrentThreadContext.getCurrentOrgCd();
			Map<String, SysDictionaryDTO> odrShopClueStatusMap = sysDictionaryApiService.searchGroupToObjMap(sysCd, orgCd, OdrShopClueInfoConstant.ODR_SHOP_CLUE_STS_CD);
			
			List<String> rgnPrList = new ArrayList<>();
			List<String> rgnCyList = new ArrayList<>();
			
			for(OdrShopClueInfoVO vo : voList){
				//经销商归属地
				if(StringUtils.isNotEmpty(vo.getSplAddressPr()) && !rgnPrList.contains(vo.getSplAddressPr())){
					rgnPrList.add(vo.getSplAddressPr());
				}
				if(StringUtils.isNotBlank(vo.getSplAddressCy()) && !rgnCyList.contains(vo.getSplAddressCy())){
					rgnCyList.add(vo.getSplAddressCy());
				}
				
				//跟进状态
				if(null != odrShopClueStatusMap.get(vo.getStatus())){
					vo.setStatusNm(odrShopClueStatusMap.get(vo.getStatus()).getCodeNm());
				}
			}
			
			List<String> rgnCdList = new ArrayList<>();
			rgnCdList.addAll(rgnCyList);
			rgnCdList.addAll(rgnPrList);
			Map<String, SysRegionDTO> rgnMap = sysRegionApiService.searchRegionByRgnCd(rgnCdList, sysCd);
			if(CollectionUtils.isMapEmpty(rgnMap)){
				rgnMap = new HashMap<>();
			}
			
			for(OdrShopClueInfoVO vo : voList){
				if(rgnMap.containsKey(vo.getSplAddressPr())){
					SysRegionDTO dto = rgnMap.get(vo.getSplAddressPr());
					vo.setRgnPrCdNm(dto.getRgnNm());
				}
				
				if(rgnMap.containsKey(vo.getSplAddressCy())){
					SysRegionDTO dto = rgnMap.get(vo.getSplAddressCy());
					vo.setRgnCyCdNm(dto.getRgnNm());
				}
			}
			page.setResultList(voList);
		}
		
		return page;
	}
	
	
	  
    /**
     * 设置组织架构名称
     *
     * @param listDTO
     * @param sysCd
     * @param orgCd
     */
    private void setOdrBscInfoOrgInfo(List<OdrShopClueInfoDTO> listDTO, String sysCd, String orgCd) {
    	List<SysOrgDTO> list = this.sysOrgApiService.searchSysOrgListBy(CurrentThreadContext.getCurrentSysCd());
    	
        Map<String, SysOrgDTO> buOrgCdMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (SysOrgDTO sysOrgDTO : list) {
                buOrgCdMap.put(sysOrgDTO.getOrgCd(), sysOrgDTO);
            }
        }
        SysOrgDTO sysOrgDTO = null;
    	//设置组织架构名称
        for (OdrShopClueInfoDTO odrShopClueInfoDTO : listDTO) { 				//客户经理组织结构     cstMgrOrgCd = 0000000100080005
            if (StringUtils.isEmpty(odrShopClueInfoDTO.getCstMgrOrgCd())){
            	continue;
            }
            String codeNm = "";
            if (null != odrShopClueInfoDTO.getBuOrgCd()) { 						//所属事业部     buOrgCd = 00000001		sysCd = 11000
                codeNm = this.sysOrgApiService.selectSysOrgNmByOrgCd(odrShopClueInfoDTO.getBuOrgCd(), sysCd);
                odrShopClueInfoDTO.setBuOrgCdNm(codeNm);						// codeNm = 重卡事业部
            }
            
            if (buOrgCdMap.containsKey(odrShopClueInfoDTO.getCstMgrOrgCd())) {
	            sysOrgDTO = buOrgCdMap.get(odrShopClueInfoDTO.getCstMgrOrgCd());
	            odrShopClueInfoDTO.setCstMgrOrgCdNm(sysOrgDTO.getOrgNm()); 		// orgNm =  蚌埠分公司
	            orgCd = sysOrgDTO.getOrgCd(); 									// orgCd = 0000000100080005
	            while(orgCd.length()>8){
	                if("4".equals(sysOrgDTO.getOrgTypCd())){					//分公司      orgTypCd  =  4
	                	odrShopClueInfoDTO.setCyOrgCdNm(sysOrgDTO.getOrgNm());	//蚌埠分公司
	                }else if("3".equals(sysOrgDTO.getOrgTypCd())){
	                	odrShopClueInfoDTO.setPrOrgCdNm(sysOrgDTO.getOrgNm());	//安徽省分公司
	                    break;
	                }
	                orgCd = orgCd.substring(0,orgCd.length()-4);				//orgCd = 000000010008
	                if(buOrgCdMap.containsKey(orgCd)){
	                    sysOrgDTO = buOrgCdMap.get(orgCd);
	                }else{
	                    break;
	                }
	            }
	        }
        }
    }

	@Override
	public List<KeyValueVO> searchStatusCdList(String odrShopClueStsCd) throws BaseException {
		return this.getKvList(odrShopClueStsCd);
	}

	
	/**
	 * 根据字典中代码组获取组员集合
	 * @param grpCd   代码组值
	 * @return
	 */
	private List<KeyValueVO> getKvList(String grpCd) {
		List<KeyValueVO> kvList = new ArrayList<>();
		try {
			List<SysDictionaryDTO> sysDictionaryDTOList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), 
					CurrentThreadContext.getCurrentOrgCd(), grpCd);
			if(CollectionUtils.isNotEmpty(sysDictionaryDTOList)){
				for(SysDictionaryDTO dto : sysDictionaryDTOList){
					KeyValueVO kvVO = new KeyValueVO();
					kvVO.setKey(dto.getCode());
					kvVO.setValue(dto.getCodeNm());
					kvList.add(kvVO);
				}
			}
		} catch (BaseException e){
			BaseLogUtils.info(logger, "getKvList", "获取字典项组"+grpCd+"失败.ERROR:"+e.getMessage(),
					CurrentThreadContext.getCurrentUserName());
		} catch (Exception e) {
			BaseLogUtils.error(logger, "getKvList", "获取字典项组"+grpCd+"失败,系统错误.ERROR:" + e.getMessage(), 
					CurrentThreadContext.getCurrentUserName());
		}
		return kvList;
	}

	@Override
	public String exportOdrShopClueInfoDetail(OdrShopClueInfoQC qc, String flServiceSysCd, String currentOrgCd) {
		if(qc == null){
			qc = new OdrShopClueInfoQC();
		}
		String path = this.odrShopClueInfoApiService.exportOdrShopClueInfoDetail(qc, flServiceSysCd, currentOrgCd);
		path = path.replace(PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH), 
				PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH));
		return path;
	}
    
    
    
}
